package net.example.lesson5.copyfile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class NioChannelCopy {
    public void copyFileByChannel(File src, File dst){
        try(FileChannel srcChannel = new FileInputStream(src).getChannel();
              FileChannel dstChannel = new FileOutputStream(dst).getChannel();
             ) {
            for(long count = srcChannel.size(); count>0;){
                long transfferred = srcChannel.transferTo(srcChannel.position(), count, dstChannel);
                srcChannel.position(srcChannel.position()+transfferred);
                count -= transfferred;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        long t1 = System.currentTimeMillis();
        NioChannelCopy copy = new NioChannelCopy();
        copy.copyFileByChannel(new File(System.getProperty("user.dir")+"\\file\\cargo.war"),
                new File(System.getProperty("user.dir")+"\\file\\cargo3.war"));
        System.out.println("耗时："+(System.currentTimeMillis()-t1));
    }
}
